package com.shao.web;

import com.shao.pojo.User;
import com.shao.service.UserService;
import com.shao.service.impl.UserServiceImpl;
import com.shao.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.http.HttpClient;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * Created with IntelliJ IDEA.
 * User: SJP
 * Date: 2021/5/16
 * Time: 16:23
 * Description: No Description
 */
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    /**
     * 注销用户
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //消毁Session中用户登录的信息
        req.getSession().invalidate();
        //重定项到首页
        resp.sendRedirect(req.getContextPath());

    }

        /**
         * 实现登录业务
         * @param req
         * @param resp
         * @throws ServletException
         * @throws IOException
         */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用xxxservice.xx方法执行业务
        User loginUser = userService.login(new User(null, username, password, null));
        if((loginUser==null)){
            //把错误信息和要回显的表单项信息，保存到request域中（键值对对象）
            req.setAttribute("msg","用户名或密码错误");
            req.setAttribute("username",username);
            //无效用户名或密码跳回登录页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }else{
            req.getSession().setAttribute("user",loginUser);
            Cookie cookie = new Cookie("username",username);
            cookie.setMaxAge(60 * 60 * 24 * 7);//当前Cookie 一周内有效
            resp.addCookie(cookie);
            //跳转到登录成功页面
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }

    }

    /**
     * 实现注册业务
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求的参数
//        String username = req.getParameter("username");
//        String password = req.getParameter("password");
//        String email = req.getParameter("email");
        String code = req.getParameter("code");
        //获取session域中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除session域中验证码，防止二次请求
        req.getSession().invalidate();
        User user = WebUtils.copyParaToBean(new User() ,req.getParameterMap());

        //验证码是否正确
        if(token !=null&&token.equalsIgnoreCase(code)){
            //检查用户名是否可用
            if(userService.existsUsername(user.getUsername())){
                System.out.println("用户名已经存在");
                //把错误信息和要回显的表单项信息，保存到request域中（键值对对象）
                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",user.getUsername());
                req.setAttribute("email",user.getEmail());
                //跳回注册页面代码
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }else{
                //可用，调用saveUser保存到数据库
                userService.registUser(new User(null,user.getUsername(),user.getPassword(),user.getEmail()));
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }
        }else{
            //不正确，跳回注册页
            System.out.println("验证码"+code+"不正确");
            //把错误信息和要回显的表单项信息，保存到request域中（键值对对象）
            req.setAttribute("msg","验证码不正确");
            req.setAttribute("username",user.getUsername());
            req.setAttribute("email",user.getEmail());
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }

    }

}
